<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MetaMask 连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .card {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        button {
            background: #f6851b;
            color: white;
            border: none;
            padding: 15px 30px;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            margin: 10px 0;
        }
        button:hover {
            background: #e2761b;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background: #f0f0f0;
            border-radius: 5px;
            word-wrap: break-word;
        }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info { background: #d1ecf1; color: #0c5460; }
        h2 { color: #333; }
    </style>
</head>
<body>
    <div class="card">
        <h2>🦊 MetaMask 连接测试</h2>
        
        <button id="checkBtn" onclick="checkMetaMask()">
            1. 检查 MetaMask 是否安装
        </button>
        
        <button id="connectBtn" onclick="connectMetaMask()" disabled>
            2. 连接 MetaMask
        </button>
        
        <button id="networkBtn" onclick="checkNetwork()" disabled>
            3. 检查网络
        </button>
        
        <div id="result" class="result info">
            点击上面的按钮开始测试...
        </div>
    </div>

    <script>
        let ethereum = window.ethereum;

        function showResult(message, type = 'info') {
            const result = document.getElementById('result');
            result.innerHTML = message;
            result.className = 'result ' + type;
        }

        function checkMetaMask() {
            if (typeof window.ethereum !== 'undefined') {
                showResult('✅ MetaMask 已安装！<br>版本: ' + window.ethereum.version, 'success');
                document.getElementById('connectBtn').disabled = false;
            } else {
                showResult('❌ 未检测到 MetaMask！<br><br>请访问 <a href="https://metamask.io/download/" target="_blank">https://metamask.io/download/</a> 安装 MetaMask', 'error');
            }
        }

        async function connectMetaMask() {
            try {
                showResult('正在连接 MetaMask...', 'info');
                
                const accounts = await ethereum.request({ 
                    method: 'eth_requestAccounts' 
                });
                
                if (accounts.length > 0) {
                    const account = accounts[0];
                    showResult(
                        `✅ 连接成功！<br><br>` +
                        `账户地址: ${account}<br>` +
                        `账户数量: ${accounts.length}`,
                        'success'
                    );
                    document.getElementById('networkBtn').disabled = false;
                } else {
                    showResult('❌ 未获取到账户', 'error');
                }
            } catch (error) {
                showResult(
                    `❌ 连接失败！<br><br>` +
                    `错误: ${error.message}<br>` +
                    `代码: ${error.code}`,
                    'error'
                );
            }
        }

        async function checkNetwork() {
            try {
                const chainId = await ethereum.request({ method: 'eth_chainId' });
                const chainIdDecimal = parseInt(chainId, 16);
                
                let networkInfo = `当前网络 Chain ID: ${chainIdDecimal} (0x${chainIdDecimal.toString(16)})<br><br>`;
                
                if (chainIdDecimal === 31337) {
                    networkInfo += '✅ 正确！已连接到 Hardhat Local 网络';
                    showResult(networkInfo, 'success');
                } else {
                    networkInfo += '❌ 错误！需要切换到 Hardhat Local 网络<br><br>';
                    networkInfo += '请在 MetaMask 中手动切换，或点击下面的按钮自动切换：<br><br>';
                    networkInfo += '<button onclick="switchToHardhat()">切换到 Hardhat Local</button>';
                    showResult(networkInfo, 'error');
                }
            } catch (error) {
                showResult(`❌ 检查网络失败: ${error.message}`, 'error');
            }
        }

        async function switchToHardhat() {
            try {
                await ethereum.request({
                    method: 'wallet_switchEthereumChain',
                    params: [{ chainId: '0x7a69' }], // 31337 in hex
                });
                showResult('✅ 已切换到 Hardhat Local 网络！', 'success');
            } catch (error) {
                if (error.code === 4902) {
                    // 网络不存在，尝试添加
                    try {
                        await ethereum.request({
                            method: 'wallet_addEthereumChain',
                            params: [{
                                chainId: '0x7a69',
                                chainName: 'Hardhat Local',
                                rpcUrls: ['http://127.0.0.1:8545'],
                                nativeCurrency: {
                                    name: 'ETH',
                                    symbol: 'ETH',
                                    decimals: 18
                                }
                            }]
                        });
                        showResult('✅ Hardhat Local 网络已添加！', 'success');
                    } catch (addError) {
                        showResult(`❌ 添加网络失败: ${addError.message}`, 'error');
                    }
                } else {
                    showResult(`❌ 切换网络失败: ${error.message}`, 'error');
                }
            }
        }

        // 页面加载时自动检查
        window.addEventListener('load', () => {
            checkMetaMask();
        });
    </script>
</body>
</html>

